package com.example.adminsystem.controller;

import com.example.adminsystem.common.ResponseResult;
import com.example.adminsystem.entity.User;
import com.example.adminsystem.mapper.UserMapper;
import com.example.adminsystem.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import com.example.adminsystem.utils.JwtTokenUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Data
    public static class LoginRequest {
        @Schema(description = "用户名", example = "test1")
        private String username;

        @Schema(description = "密码", example = "123456")
        private String password;

    }

    @Data
    public static class RegisterRequest {
        @Schema(description = "用户名", example = "test1")
        private String username;

        @Schema(description = "昵称", example = "测试用户")
        private String nickname;

        @Schema(description = "密码", example = "123456")
        private String password;

        @Schema(description = "邮箱", example = "<EMAIL>")
        private String email;

    }
    @Operation(summary = "登录", description = "用户登录")
    @PostMapping("/login")
    public ResponseResult<?> login(@RequestBody LoginRequest item) {
        User user = userMapper.selectUserinfo(item.getUsername());
        if (user != null && passwordEncoder.matches(item.getPassword(), user.getPassword())) {
            String token = jwtTokenUtil.generateToken(user);
            String refreshToken = jwtTokenUtil.generateRefreshToken(user);
            Map<String, Object> result = new HashMap<>();
            Map<String, Object> roles = new HashMap<>();
            result.put("accessToken", token);
            result.put("refreshToken", refreshToken);
            result.put("username", user.getUsername());
            result.put("nickname", user.getNickname());
            result.put("roles", roles);
            // 过期时间需要标准的时间格式："2024/07/20 12:45:36"
            Date expiration = jwtTokenUtil.getExpirationDateFromToken(token);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); // 设置时区
            result.put("expires", sdf.format(expiration)); // 使用格式化后的时间
            return ResponseResult.success(result);
        }
        return ResponseResult.error("用户名或密码错误");
    }

    @Operation(summary = "注册用户", description = "注册用户")
    @PostMapping("/register")
    public ResponseResult<User> register(@RequestBody RegisterRequest item) {
        User user = new User();
        user.setUsername(item.getUsername());
        user.setNickname(item.getNickname());
        user.setPassword(item.getPassword());
        user.setEmail(item.getEmail());
        return ResponseResult.success(userService.saveUser(user));
    }

    @Operation(summary = "Swagger认证", description = "用于Swagger UI的OAuth2认证")
    @PostMapping
    public Map<String, Object> swaggerAuth(LoginRequest item) {
        User user = userMapper.selectUserinfo(item.getUsername());
        if (user != null && passwordEncoder.matches(item.getPassword(), user.getPassword())) {
            String token = jwtTokenUtil.generateToken(user);
            Map<String, Object> result = new HashMap<>();
            result.put("access_token", token);
            result.put("token_type", "bearer");
            // 过期时间需要标准的时间格式："2024/07/20 12:45:36"
            Date expiration = jwtTokenUtil.getExpirationDateFromToken(token);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); // 设置时区
            result.put("expires", sdf.format(expiration)); // 使用格式化后的时间
            return result;
        }
        throw new RuntimeException("用户名或密码错误");
    }
}
